/**
 * 
 */
package info.niwota.frames;

import info.niwota.frames.Dialogs.ItemInfo;
import info.niwota.frames.Dialogs.ItemListAdapter;
import info.niwota.webapp.InstallHotwebActivity;
import info.niwota.webapp.WebIntents;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

/**
 * @author qiangli
 * 
 */
public class PickPeerFrameActivity extends Activity {
	private static final int RC_PICK_PEER = 1;
	private static final String TAG = "PickPeerFrameActivity";
	private static final boolean DEBUG = Debug.DEBUG;

	private static final int DIALOG_LISTPEERFRAME = 17;

	private static final int DIALOG_MESSAGE = 18;

	private Dialog diaMessage;

	private Dialog diaPeerFrames;

	private ItemListAdapter peerAdapter;

	private String peer;

	private int status;

	private ProgressMonitor progressMonitor = new ProgressMonitor();

	private Handler progressHandler = new Handler() {
		public void handleMessage(Message msg) {
			CharSequence m = progressMonitor.message;
			if (DEBUG) {
				Log.d(TAG, "message: " + m);
			}
			diaPeerFrames.setTitle(m);
		}
	};
	private CharSequence message;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setFullScreen();
		
		// default
		setResult(RESULT_CANCELED);

		Intent data = getIntent();
		final String peer = data.getStringExtra(WebIntents.EXTRA_PEER);

		if (TextUtils.isEmpty(peer)) {
			doPickPeer();
		} else {
			doListPeerFrame(data);
		}
	}

	private void setFullScreen() {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
	}

	private void doPickPeer() {
		try {
			if (InstallHotwebActivity.ensure(this)) {
				Intent i = new Intent();
				i.setClassName("info.niwota.web",
						"info.niwota.web.user.PickUserActivity");
				startActivityForResult(i, RC_PICK_PEER);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_LISTPEERFRAME:
			diaPeerFrames = createPeerFramesDialog();
			return diaPeerFrames;
		case DIALOG_MESSAGE:
			diaMessage = createMessageDialog();
			return diaMessage;
		default:
		}
		return null;
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (Debug.DEBUG) {
			Log.d(TAG, "onActivityResult requestCode: " + requestCode
					+ " resultCode:" + resultCode + " == " + RESULT_OK
					+ " data: " + data);
		}

		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case RC_PICK_PEER:
				doListPeerFrame(data);
				return;
			default:
			}
		}
		
		doCancel();
	}

	private void doListPeerFrame(Intent data) {
		if (DEBUG) {
			Log.d(TAG,
					"doListPeerFrame: " + data + " extras: " + data.getExtras());
		}
		peer = data.getStringExtra(WebIntents.EXTRA_PEER);
		status = data.getIntExtra(WebIntents.EXTRA_STATUS, 0);

		// if (status == 0) {
		// Toast.makeText(this, getString(R.string.msg_peer_not_available,
		// peer), Toast.LENGTH_SHORT).show();
		// return;
		// }

		// load data
		showDialog(DIALOG_LISTPEERFRAME);
	}

	private Dialog createPeerFramesDialog() {
		final Context ctx = this;
		peerAdapter = new ItemListAdapter(this) {
			public void loadItems(final Context context,
					final List<ItemInfo> list) {

				final Thread th = new Thread() {
					public void run() {
						try {
							JSONObject jo = FrameHelper
									.getPeerFrames(ctx, peer);

							if (DEBUG) {
								Log.d(TAG, "peer frame object: " + jo);
							}
							JSONArray ja = jo.getJSONArray("frames");
							int len = ja.length();
							for (int i = 0; i < len; i++) {
								JSONObject fo = ja.getJSONObject(i);
								String name = fo.getString("label");

								ItemInfo item = new ItemInfo();
								item.setTitle(name);
								item.setIcon(null);
								item.setObject(fo);
								//
								list.add(item);
							}
							if (progressMonitor != null
									&& !progressMonitor.isAborted()) {
								runOnUiThread(new Runnable() {
									public void run() {
										peerAdapter.notifyDataSetChanged();
										diaPeerFrames.setTitle(peer);
									}
								});
							}
							progressMonitor.clear();
						} catch (Exception e) {
							e.printStackTrace();
							//
							diaPeerFrames.dismiss();

							loadError(e);
						}
					}

					private void loadError(final Exception e) {
						runOnUiThread(new Runnable() {
							public void run() {
								final CharSequence msg = getString(
										R.string.err_fail, e.getMessage());
								showLoadErrorDialog(msg);
							}
						});
					}
				};
				th.start();
				//
				final long startTime = System.currentTimeMillis();
				Runnable task = new Runnable() {
					public void run() {
						try {
							th.interrupt();
						} catch (Exception e) {
							e.printStackTrace();
						}
						try {
							diaPeerFrames.dismiss();
						} catch (Exception e) {
							e.printStackTrace();
						}

						final CharSequence errMsg = getString(
								R.string.err_connect_fail, peer);

						showLoadError(errMsg);

						if (DEBUG) {
							Log.d(TAG,
									" time is up: "
											+ (System.currentTimeMillis() - startTime));
						}
					}

				};
				progressMonitor.start(progressHandler, 1 * 60 * 1000, task);
			}

			private void showLoadError(CharSequence s) {
				Toast.makeText(ctx, s, Toast.LENGTH_SHORT).show();
			}

			public void onClick(DialogInterface dialog, int which) {
				if (DEBUG) {
					Log.d(TAG, "onClick which:  " + which);
				}

				ItemInfo item = getItem(which);
				String label = null;
				long lastModified = 0;
				if (item != null) {
					JSONObject jo = (JSONObject) item.getObject();
					try {
						label = (String) jo.getString("label");
						lastModified = jo.getLong("lastModified");
					} catch (JSONException e) {
						e.printStackTrace();

						return;
					}

				}
				if (DEBUG) {
					Log.d(TAG, "onClick frame label: " + label
							+ " lastModified: " + lastModified);
				}

				Intent data = new Intent();
				data.putExtra(WebIntents.EXTRA_PEER, peer);
				data.putExtra(WebIntents.EXTRA_LABEL, label);
				data.putExtra(WebIntents.EXTRA_LAST_MODIFIED, lastModified);
				
				doFinish(data);
			}
		};

		CharSequence msg = ctx.getText(R.string.text_please_wait);
		AlertDialog d = Dialogs.create(ctx, msg, peerAdapter);

		d.setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				progressMonitor.abort();
				doCancel();
			}
		});

		return d;
	}

	protected void doCancel() {
		setResult(RESULT_CANCELED);
		finish();
	}

	protected void doFinish(Intent data) {
		setResult(RESULT_OK, data);
		finish();
	}

	private void showLoadErrorDialog(CharSequence msg) {
		this.message = msg;
		showDialog(DIALOG_MESSAGE);
	}

	private Dialog createMessageDialog() {
		return new AlertDialog.Builder(this)
        .setIcon(R.drawable.ic_dialog_menu_generic)
        .setTitle("")
        .setMessage("")
        .setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface arg0) {
				doCancel();
			}
        })
        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	doCancel();
            }
        }).create();
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		if (id == DIALOG_LISTPEERFRAME) {
			final Window w = dialog.getWindow();

			w.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
			// Issue 3674
			w.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
					WindowManager.LayoutParams.FLAG_FULLSCREEN);
		}
		switch (id) {
		case DIALOG_LISTPEERFRAME:
			if (peerAdapter != null) {
				peerAdapter.reload();
			}
			break;
		case DIALOG_MESSAGE:
			AlertDialog ad = (AlertDialog) dialog;
			ad.setMessage(message);
			break;
		}
	}
}
